import { DesignerContext, MasterPageContext, MasterPage, ComponentData, ComponentProps } from "maishu-jueying";
import React = require("react");
import { component } from "./common/component";
import { MyPageDesigner } from "controls/design-view";
import { ETIME } from "constants";

@component()
export class ComponentContainer extends React.Component<ComponentProps<any>> {
    private element: HTMLElement;
    private designer: MyPageDesigner;
    private master: MasterPage;

    componentDidMount() {
        if (this.designer == null)
            return;

        let pageData = this.designer.pageData;
        let elementId = (this.props as any).id;
        console.assert(elementId != null);
        console.assert(document.getElementById(elementId));
        console.log(`ComponentContainer:${elementId}`);
        $(this.element).sortable({
            axis: "y",
            stop: () => {
                //==============================================================================================
                // 对组件进行排序
                console.assert(pageData.children != null);

                let childComponentDatas: ComponentData[] = [];
                let elements = this.element.querySelectorAll("li");
                for (let i = 0; i < elements.length; i++) {

                    let childId = elements[i].getAttribute("data-component-id");
                    if (!childId)
                        continue;

                    console.assert(childId != null);

                    let child = pageData.children.filter(o => o.props.id == childId)[0];
                    console.assert(child != null);

                    childComponentDatas.push(child);
                }

                let childIds = childComponentDatas.map(o => o.props.id);
                pageData.children = pageData.children.filter(o => childIds.indexOf(o.props.id) < 0);

                pageData.children.push(...childComponentDatas);
                //==============================================================================================

            },
            receive: (event, ui) => {
                let componentData: ComponentData = JSON.parse(ui.helper.attr("component-data"));
                console.assert(this.master.props.id);
                console.assert(this.props.id != null);
                componentData.props.parentId = this.props.id;


                let elementIndex: number = 0;
                ui.helper.parent().children().each((index, element) => {
                    if (element == ui.helper[0]) {
                        elementIndex = index;
                        return false;
                    }
                })


                let isFirst = elementIndex == 0;
                let isLatest = elementIndex == ui.helper.parent().children().length - 1;

                if (isFirst) {
                    this.designer.appendComponent(this.master.props.id, componentData, 0);
                }
                else if (isLatest) {
                    this.designer.appendComponent(this.master.props.id, componentData);
                }
                else {
                    let nextComponentDataId = ui.helper.parent().children()[elementIndex].getAttribute("data-component-id");
                    let componentIds = pageData.children.map(o => o.props.id);
                    let nextComponentDataIndex = componentIds.indexOf(nextComponentDataId);
                    console.assert(nextComponentDataId != null);
                    this.designer.appendComponent(this.master.props.id, componentData, nextComponentDataIndex);
                }


                ui.helper.remove();
            }
        })

        this.designer.componentPanel.attach((componentPanel) => {
            if (componentPanel == null)
                return;
                
            setTimeout(() => {
                componentPanel.addDropTarget(this.element);
            }, 1000)
        })
    }
    render() {
        return <MasterPageContext.Consumer>
            {args => {
                let master = this.master = args.master;
                let children: (React.ReactElement<any,any> | string)[] = []
                if (master.props && master.props.children) {
                    let arr: React.ReactElement<ComponentProps<any>>[]
                    if (Array.isArray(master.props.children)) {
                        arr = master.props.children as any
                    }
                    else {
                        arr = [master.props.children as any]
                    }
                    children = arr.filter((o) => o.props.parentId != null && o.props.parentId == (this.props as any).id)
                }

                return <DesignerContext.Consumer>
                    {args => {
                        this.designer = args.designer as MyPageDesigner;
                        if (!this.designer) {
                            return children;
                        }
                        return <ul ref={e => this.element = this.element || e}>
                            {children.map((o: any, i) =>
                                <li data-component-id={o.props ? o.props.id : ""} key={o.props ? o.props.id : i}>{o}</li>
                            )}
                        </ul>
                    }}
                </DesignerContext.Consumer>
            }}
        </MasterPageContext.Consumer>
    }
}